/**
 *
 */
package contest.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {

    final MailConfig mailConfigTO;

    public MailSender(MailConfig mailConfigTO) {
        this.mailConfigTO = mailConfigTO;
    }

    public void send(String mailTo, String mailCC,
            String subject, String content) throws MessagingException {

        Properties props = System.getProperties();
        props.setProperty("mail.transport.protocol", mailConfigTO.getMailTransportProtocol());
        props.setProperty("mail.host", mailConfigTO.getMailHost());
        props.put("mail.smtp.socketFactory.port", mailConfigTO.getMailSmtpSocketFactoryPort());

        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        Session session = Session.getInstance(props, new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        mailConfigTO.getMailSystem(), mailConfigTO.getPassMailSystem());
            }
        });
        Message message = new MimeMessage(session);
        Address fromAdd = new InternetAddress(mailConfigTO.getMailSystem());
        message.setFrom(fromAdd);
        if (!mailTo.equals("")) {
            Address toAdd = new InternetAddress(mailTo);
            message.setRecipient(Message.RecipientType.TO, toAdd);
        }
        if (!mailCC.equals("")) {
            Address ccAdd = new InternetAddress(mailCC);
            message.setRecipient(Message.RecipientType.CC, ccAdd);
        }
        message.setSubject(subject);

        MimeBodyPart messagePart = new MimeBodyPart();
        MimeMultipart multipart = new MimeMultipart();

        multipart.addBodyPart(messagePart);  // adding message part
        //Setting the Email Encoding
        messagePart.setText(content);
        messagePart.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
        messagePart.setHeader("Content-Transfer-Encoding", "quoted-printable");

        message.setContent(multipart);
        message.setSentDate(new Date());
        if (!mailTo.equals("")) {
            Transport.send(message);
        }

    }
}
